<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

class UserLesson extends Model
{
    const PROGRESS = [
        'read'      => 'read', // 读绘本
        'word'      => 'word', // 学单词
        'essence' => 'essence', // 精读
        'dub'       => 'dub', // 配音
        'game'      => 'game', // 闯关游戏
    ];

    protected $table = 'user_lessons';

    protected $fillable = ['user_id', 'lesson_id', 'progress', 'course_id'];

    // ============= relations ==========



    // ============= scope ==========
    public function scopeOfUserCourseLessons($query, $userId, $courseId)
    {
        return $query->where('user_id', $userId)->where('course_id', $courseId);
    }


    public function scopeOfUserCourseOfficialLessons($query, $userId, $courseId)
    {
        return $query->where('user_id', $userId)->where('course_id', $courseId)->where('sequence', '!=', 0);
    }


    public function scopeOfUserCourseEnableLessons($query, $userId, $courseId, $enableTime)
    {
        return $query->where('user_id', $userId)->where('course_id', $courseId)->where('enable_time', '<=', $enableTime);
    }

    public function scopeOfUserLesson($query, $userId, $lessonId)
    {
        return $query->where('user_id', $userId)->where('lesson_id', $lessonId);
    }

    public function scopeOfUserHistory($query, $userId)
    {
        return $query->where('user_id', $userId)->whereNotNull('last_study_time')->orderBy('last_study_time', 'desc');
    }

    public function scopeOfUserDub($query, $userId)
    {
        return $query->where('user_id', $userId)->where('is_dub', static::IS_TRUE);
    }

    // ============= fields ==========


    public function getUserId()
    {
        return $this->user_id;
    }

    public function getCourseId()
    {
        return $this->course_id;
    }

    public function setCourseId($courseId)
    {
        $this->course_id = $courseId;
    }

    public function getLessonId()
    {
        return $this->lesson_id;
    }

    public function setLessonId($lessonId)
    {
        $this->lesson_id = $lessonId;
    }

    public function setUserId($userId)
    {
        $this->user_id = $userId;
    }

    public function setDubScore($score)
    {
        $this->dub_score = $score;
    }

    public function getDubScore()
    {
        return $this->dub_score;
    }

    public function setDubStar($star)
    {
        $this->dub_star = $star;
    }


    public function getDubStar()
    {
        return $this->dub_star;
    }

    public function setScore($score)
    {
        $this->score = $score;
    }

    public function getStar()
    {
        return $this->star;
    }

    public function setStar($star)
    {
        $this->star = $star;
    }

    public function getKnowledgeCount()
    {
        return $this->knowledge_count;
    }

    public function setKnowledgeCount($knowledgeCount)
    {
        $this->knowledge_count = $knowledgeCount;
    }

    public function setEssenceQaCount($count)
    {
        $this->essence_qa_count = $count;
    }
    public function getEssenceQaCount()
    {
        return $this->essence_qa_count;
    }

    public function setGameTestCount($count)
    {
        $this->game_test_count = $count;
    }
    public function getGameTestCount()
    {
        return $this->game_test_count;
    }

    public function setGameWordCount($count)
    {
        $this->game_word_count = $count;
    }

    public function getGameWordCount()
    {
        return $this->game_word_count;
    }

    public function getGameScore()
    {
        return $this->game_score;
    }

    public function setGameScore($score)
    {
        $this->game_score = $score;
    }

    public function getEssenceScore()
    {
        return $this->essence_score;
    }

    public function setEssenceScore($score)
    {
        $this->essence_score = $score;
    }


    public function getProgress()
    {
        return $this->progress;
    }

    public function setProgress($progress)
    {
        $this->progress = $progress;
    }

    public function setSequence($sequence)
    {
        $this->sequence = $sequence;
    }

    public function getSequence()
    {
        return $this->sequence;
    }

    public function getStudyStatus()
    {
        if ($this->progress == static::PROGRESS['game']) {
            return 2;
        }
        if ($this->progress || $this->last_study_time) {
            return 1;
        } else {
            return 0;
        }
    }

    public function getIsDub()
    {
        return $this->is_dub;
    }

    public function setIsDub($status)
    {
        $this->is_dub = $status;
    }

    public function setLastDubTime($time)
    {
        $this->last_dub_time = $time;
    }

    public function getLastDubTime()
    {
        return $this->last_dub_time;
    }

    public function setEssenceHitCount($count)
    {
        $this->essence_hit_count = $count;
    }

    public function setGameHitCount($count)
    {
        $this->game_hit_count = $count;
    }

    public function setPlayGameTime($time)
    {
        $this->play_game_time = $time;
    }

    public function getPlayGameTime()
    {
        return $this->play_game_time;
    }

    public function getFirstStudyTime()
    {
        return $this->first_study_time;
    }

    public function setFirstStudyTime($time)
    {
        $this->first_study_time = $time;
    }

    public function setLastStudyTime($time)
    {
        $this->last_study_time = $time;
    }

    public function getLastStudyTime()
    {
        return $this->last_study_time;
    }

    public function setEnableTime($time)
    {
        $this->enable_time = $time;
    }

    public function getEnableTime()
    {
        return $this->enable_time;
    }

    public function getHistoryCategory()
    {
        // “今天”“昨天”“三天前”“一周前”和“一个月前”
        $lastStudyTime = Carbon::parse(date('Y-m-d', strtotime($this->last_study_time)));
        $diffDays = $lastStudyTime->diffInDays(Carbon::today());
        if ($diffDays === 0) {
            return '今天';
        } elseif ($diffDays === 1) {
            return '昨天';
        } elseif ($diffDays >= 2 && $diffDays <=6) {
            return '三天前';
        } elseif ($diffDays >= 7 && $diffDays <= 29) {
            return '一周前';
        } else {
            return '一个月前';
        }
    }

    public function setWordCount($wordCount)
    {
        $this->word_count = $wordCount;
    }

    public function getWordCount()
    {
        return $this->word_count;
    }

    public static function getGameWinner($lessonId)
    {
        return static::query()->where('lesson_id', $lessonId)->where('play_game_time', '>', 0)->orderBy('play_game_time', 'asc')->first();
    }


    public static function isWinner($userId, $lessonId)
    {
        $redisKeyWinner = 'lesson_winner_' . $lessonId;
        // 优先取redis缓存中的winner数据
        $winner = Redis::hgetall($redisKeyWinner);
        if ($winner) {
            return $userId == $winner['user_id'];
        } else {
            // redis中没有，再从数据库中
            /** @var UserLesson $winner */
            $winner = static::getGameWinner($lessonId);
            return $userId == $winner->getUserId();
        }
    }

    public static function isFinishedUserCourseLessons($userId, $courseId)
    {
        // 体验课不算在内
        $query = static::query()->where([
            'user_id'   => $userId,
            'course_id' => $courseId,
        ])->where('sequence', '!=', 0);
        // progress为null
        if ($query->whereNull('progress')->exists()) {
            return false;
        }
        // progress不为null
        return !static::query()->where([
            'user_id'   => $userId,
            'course_id' => $courseId,
        ])->where('progress', '!=', static::PROGRESS['game'])->exists();
    }

    public static function convertTime($seconds)
    {
        $minutes = floor($seconds / 60);
        $secondsLeft = $seconds % 60;
        if($minutes < 10) {
            $minutes = "0" . $minutes;
        }
        if( $secondsLeft <10 ) {
            $secondsLeft = "0" . $secondsLeft;
        }
        return "{$minutes}分{$secondsLeft}秒";
    }

    public static function getNextLessonId($userId, $courseId, $id)
    {
        return static::query()->where('user_id', $userId)->where('course_id', $courseId)->where('id', '>', $id)->orderBy('id', 'asc')->value('lesson_id');
    }

    public static function getProgressIndex($progress)
    {
        return array_search($progress, array_values(static::PROGRESS));
    }
}
